<?php

// $Id: template.php,v 1.12.2.1 2007/01/17 05:28:41 jjeff Exp $

/**
 * @file
 * File which contains theme overrides for the Zen theme.
 */

/*
 * ABOUT
 *
 *  The template.php file is one of the most useful files when creating or modifying Drupal themes.
 *  You can add new regions for block content, modify or override Drupal's theme functions, 
 *  intercept or make additional variables available to your theme, and create custom PHP logic.
 *  For more information, please visit the Theme Developer's Guide on Drupal.org:
 *  http://drupal.org/node/509
 */

/*
 * MODIFYING OR CREATING REGIONS
 *
 * Regions are areas in your theme where you can place blocks.
 * The default regions used in themes  are "left sidebar", "right sidebar", "header", and "footer",  although you can create
 * as many regions as you want.  Once declared, they are made available to the page.tpl.php file as a variable.  
 * For instance, use <?php print $header ?> for the placement of the "header" region in page.tpl.php.
 * 
 * By going to  the administer > site building > blocks page you can choose which regions various blocks should be placed.
 * New regions you define here will automatically show up in the drop-down list by their human readable name.
 */

/*
 * Declare the available regions implemented by this engine.
 *
 * @return
 *    An array of regions.  The first array element will be used as the default region for themes.
 *    Each array element takes the format: variable_name => t('human readable name')
 */

include_once("includes/views_theme_functions.php");

function zen_regions() {
  return array (
    'left' => t('left sidebar'
  ), 'right' => t('right sidebar'), 'content_top' => t('content top'), 'content_bottom' => t('content bottom'), 'header' => t('header'), 'footer' => t('footer'), 'secondary' => t('secondary'), 'contentleft' => t('contentleft'), 'contentright' => t('contentright'), 'mygambesimenu_vertical' => t('my vertical gambesimenu'), 'mygambesimenu_horizontal' => t('my horizontal gambesimenu'), 'categories' => t('categories_menu'),);
}

/*
 * OVERRIDING THEME FUNCTIONS
 *
 *  The Drupal theme system uses special theme functions to generate HTML output automatically.
 *  Often we wish to customize this HTML output.  To do this, we have to override the theme function.
 *  You have to first find the theme function that generates the output, and then "catch" it and modify it here.
 *  The easiest way to do it is to copy the original function in its entirety and paste it here, changing
 *  the prefix from theme_ to zen_.  For example:
 *
 *   original:  theme_breadcrumb() 
 *   theme override:   zen_breadcrumb()
 *
 *  See the following example. In this theme, we want to change all of the breadcrumb separator links from  >> to ::
 *
 */

/**
 * Return a themed breadcrumb trail.
 *
 * @param $breadcrumb
 *   An array containing the breadcrumb links.
 * @return a string containing the breadcrumb output.
 */
function zen_breadcrumb($breadcrumb) {
  if (!empty ($breadcrumb)) {
    return '<div class="breadcrumb">' . implode(' :: ', $breadcrumb) . '</div>';
  }
}

/* 
 * CREATE OR MODIFY VARIABLES FOR YOUR THEME
 *
 *  The most powerful function available to themers is the _phptemplate_variables() function. It allows you
 *  to pass newly created variables to different template (tpl.php) files in your theme. Or even unset ones you don't want
 *  to use.
 *
 *  It works by switching on the hook, or name of the theme function, such as:
 *    - page
 *    - node
 *    - comment
 *    - block
 *
 * By switching on this hook you can send different variables to page.tpl.php file, node.tpl.php
 * (and any other derivative node template file, like node-forum.tpl.php), comment.tpl.php, and block.tpl.php
 *
 */

/**
 * Intercept template variables
 *
 * @param $hook
 *   The name of the theme function being executed
 * @param $vars
 *   A sequential array of variables passed to the theme function.
 */

function _phptemplate_variables($hook, $vars = array ()) {
  switch ($hook) {
    // Send a new variable, $logged_in, to page.tpl.php to tell us if the current user is logged in or out.
    case 'page' :
      // get the currently logged in user
      global $user;

      // An anonymous user has a user id of zero.      
      if ($user->uid > 0) {
        // The user is logged in.
        $vars['logged_in'] = TRUE;
      } else {
        // The user has logged out.
        $vars['logged_in'] = FALSE;
      }

      $body_classes = array ();
      // classes for body element
      // allows advanced theming based on context (home page, node of certain type, etc.)
      $body_classes[] = ($vars['is_front']) ? 'front' : 'not-front';
      $body_classes[] = ($vars['logged_in']) ? 'logged-in' : 'not-logged-in';
      if ($vars['node']->type) {
        $body_classes[] = 'ntype-' . zen_id_safe($vars['node']->type);
      }
      switch (TRUE) {
        case $vars['sidebar_left'] && $vars['sidebar_right'] :
          $body_classes[] = 'both-sidebars';
          break;
        case $vars['sidebar_left'] :
          $body_classes[] = 'sidebar-left';
          break;
        case $vars['sidebar_right'] :
          $body_classes[] = 'sidebar-right';
          break;
      }

      // implode with spaces
      $vars['body_classes'] = implode(' ', $body_classes);

      switch (arg(0)) {
        // put e-commerce related stuffs here, ie other stuffs like blogs go somewhere else
        case 'vecommerce' :
          switch (arg(1)) {
            case 'sellers' :
              $vars['template_file'] = 'page-vecommerce-forbuyers-sellers';
              break;

            case 'catalogs' :
              $vars['template_file'] = 'page-vecommerce-forbuyers-catalogs';
              break;

            case 'sellingleads' :
              $vars['template_file'] = 'page-mygambesi';
              break;

            case 'buyingleads' :
              $vars['template_file'] = 'page-mygambesi';
              break;
          }
          break;

        case 'mygambesi' :
          global $user;
          $vars['uid'] = $user->uid;
          $vars['template_file'] = 'page-mygambesi';
          break;

        case 'privatemsg' :
          $vars['template_file'] = 'page-mygambesi';
          break;

        case 'user' :
          global $user;
          $vars['uid'] = $user->uid;
          $vars['template_file'] = 'page-mygambesi';
          break;

        case 'node' :
          switch (arg(1)) {
            case 'add' :
              switch (arg(2)) {
                case 'product' :
                  $vars['template_file'] = 'page-mygambesi';
                  break;
                case 'buyingleads' :
                  $vars['template_file'] = 'page-mygambesi';
                  break;
              }
          }

      }

      break;

    case 'node' :
      // get the currently logged in user
      global $user;

      // set a new $is_admin variable
      // this is determined by looking at the currently logged in user and seeing if they are in the role 'admin'
      $vars['is_admin'] = in_array('admin', $user->roles);

      $node_classes = array (
        'node'
      );
      if ($vars['sticky']) {
        $node_classes[] = 'sticky';
      }
      if (!$vars['node']->status) {
        $node_classes[] = 'node-unpublished';
      }
      $node_classes[] = 'ntype-' . zen_id_safe($vars['node']->type);
      // implode with spaces
      $vars['node_classes'] = implode(' ', $node_classes);

      break;

    case 'comment' :
      // we load the node object that the current comment is attached to
      $node = node_load($vars['comment']->nid);
      // if the author of this comment is equal to the author of the node, we set a variable
      // then in our theme we can theme this comment differently to stand out
      $vars['author_comment'] = $vars['comment']->uid == $node->uid ? TRUE : FALSE;
      break;
  }

  return $vars;
}

/**
* Converts a string to a suitable html ID attribute.
* - Preceeds initial numeric with 'n' character.
* - Replaces space and underscore with dash.
* - Converts entire string to lowercase.
* - Works for classes too!
* 
* @param string $string
*  the string
* @return
*  the converted string
*/
function zen_id_safe($string) {
  if (is_numeric($string {
    0 })) {
    // if the first character is numeric, add 'n' in front
    $string = 'n' . $string;
  }
  return strtolower(preg_replace('/[^a-zA-Z0-9-]+/', '-', $string));
}





/**
 * @param array $vars
 * should contain 'sellerslist' element 
 * - themed output of views_view_list_sellingleads
 */
function phptemplate_sellers_show_sellerslist($vars) {
  return _phptemplate_callback('customview-vecommerce-sellers', $vars);
}

/**
 * Themeing the view for the display of the products taxonomywise
 */


function phptemplate_sellingleads_add_categorytree_show() {
  drupal_set_title(t('Select category for new product post'));
  drupal_add_css(path_to_theme() . '/sellingleads_add_categorytree_show.css');
  //selecting root level terms from the taxonomy hierarchy having parent id 0, that is no parent
  //only add links to leaf categories
  $output = '';
  //Select the action from the url and perform respectiv function of adding either selling
  //leads or buying leads or display the products
  $action_argument = arg(2);

  // a taxonomy vocabulary called vecommerce should be already available
  // get the vid of vecommerce and get its children
  $vocabularyname = "vecommerce";
  $vid = db_fetch_array(db_query("SELECT vid FROM {vocabulary} WHERE LOWER(name) = '%s'", VECOMMERCE_VOCABULARY_NAME));

  // get root elements of vocabulary vecommerce
  $root_terms = taxonomy_get_children(0, $vid['vid']);
  foreach ($root_terms as $root_id => $root_value) {
    

    //$node_count = taxonomy_term_count_nodes($root_value->tid,'product');
    $children = taxonomy_get_children($root_id);

	  // show link only if leaf element
	  if (empty ($children)) {
	    $output .= '<ul><li>' . l($root_value->name, 'node/add/product/' . sellingleads_add_getptypehandler($root_id) . '/' . $root_value->tid) . '</li></ul>';
	  } else {
	    $output .= '<ul><li>' . t($root_value->name);
	    $children_level_one = $children;
	
	    foreach ($children_level_one as $children_key_level_one => $children_value_level_one) {
	      $children_level_two = taxonomy_get_children($children_key_level_one);
	      if (empty ($children_level_two)) {
	        $output .= '<ul class="ul-leaf"><li class="li-leaf">' . l($children_value_level_one->name, 'node/add/product/' . sellingleads_add_getptypehandler($children_key_level_one) . '/' . $children_key_level_one) . '</li></ul>';
	      } else {
	        $output .= '<ul><li>' . t($children_value_level_one->name);
	        $output .= '<ul class="ul-leaf">';
	        foreach ($children_level_two as $children_key_level_two => $children_value_level_two) {
	          $output .= '<li class="li-leaf">' . l($children_value_level_two->name, 'node/add/product/' . sellingleads_add_getptypehandler($children_key_level_two) . '/' . $children_key_level_two) . '</li>';
	        }
	        $output .= '</ul></li></ul>';
	      }
    
	    }
	    $output .= '</li></ul>';
	    //$node_count_one = taxonomy_term_count_nodes($children_one_value->tid,'product');  
	  }
  }
  return $output;
}

function phptemplate_buyingleads_add_categorytree_show() {
  drupal_set_title(t('Select category of new post to buy'));
  drupal_add_css(path_to_theme() . '/buyingleads_add_categorytree_show.css');
  //selecting root level terms from the taxonomy hierarchy having parent id 0, that is no parent
  //only add links to leaf categories
  $output = '';
  //Select the action from the url and perform respectiv function of adding either selling
  //leads or buying leads or display the products
  $action_argument = arg(2);

  // a taxonomy vocabulary called vecommerce should be already available
  // get the vid of vecommerce and get its children
  $vocabularyname = "vecommerce";
  $vid = db_fetch_array(db_query("SELECT vid FROM {vocabulary} WHERE LOWER(name) = '%s'", VECOMMERCE_VOCABULARY_NAME));

  // get root elements of vocabulary vecommerce
  $root_terms = taxonomy_get_children(0, $vid['vid']);
  foreach ($root_terms as $root_id => $root_value) {
    
    //$node_count = taxonomy_term_count_nodes($root_value->tid,'product');
    $children = taxonomy_get_children($root_id);

	  // show link only if leaf element
	  if (empty ($children)) {
	    $output .= '<ul><li>' . l($root_value->name, 'node/add/buyingleads/' . $root_value->tid) . '</li></ul>';
	  } else {
	    $output .= '<ul><li>' . t($root_value->name);
	    $children_level_one = $children;
	    
	    $output .= '<ul class="ul-leaf">';
	    foreach ($children_level_one as $children_key_level_one => $children_value_level_one) {
	      $children_level_two = taxonomy_get_children($children_key_level_one);
	      
	      if (empty ($children_level_two)) {
	        $output .= '<li class="li-leaf">' . l($children_value_level_one->name, 'node/add/buyingleads/' . $children_key_level_one) . '</li>';
	      } else {
	
	        $output .= '<li>' . t($children_value_level_one->name);
	        $output .= '<ul class="ul-leaf">';
	        foreach ($children_level_two as $children_key_level_two => $children_value_level_two) {
	          $output .= '<li class="li-leaf">' . l($children_value_level_two->name, 'node/add/buyingleads/' . $children_key_level_two) . '</li>';
	        }
	        $output .= '</ul></li>';
	      }
	    }
	    $output .= '</ul>';
	    $output .= '</li></ul>';
	  }
  }
  return $output;
}

/**
 * Implementation of theme functions
 */
function phptemplate_category_list($root_terms) {

  $arg0 = arg(0); //should be vecommerce
  $arg1 = arg(1); // if sellers then product else buyingleads
  $option = '';
  $content_type = '';
  if ($arg0 == 'vecommerce') {
    $option = $arg1;
    if ($arg1 == 'sellers') {
      $content_type = 'product';
    } else {
      $content_type = 'buyingleads';
    }
  }

  if ((empty ($option)) || empty ($content_type)) {
    $option = 'sellers';
    $content_type = 'product';
  }

  $output .= '<ul>';

  foreach ($root_terms as $root_key => $root_value):
    $nodes_count = category_term_count_nodes($root_value->tid, $content_type);


  $children = taxonomy_get_children($root_value->tid);
  if (empty ($children)) {
    $output .= '<li>' . l($root_value->name . '(' . $nodes_count . ')', 'vecommerce/' . $option . '/' . $root_value->tid) . '</li>';
  } else {
    $output .= '<li>' . $root_value->name . '(' . $nodes_count . ')';
    $output .= '<ul>';
    foreach ($children as $child)
      : $nodes_child_count = category_term_count_nodes($child->tid, $content_type);
    $output .= '<li>' . l($child->name . '(' . $nodes_child_count . ')', 'vecommerce/' . $option . '/' . $child->tid) . '</li>';
    endforeach;
    $output .= '</ul></li>';
  }
  endforeach;
  $output .= '</ul>';
  return $output;
}

function phptemplate_sellers_show_catalogs(& $displayArray, $tid = 0) {
  
  drupal_set_title(t('Browse Products On Sale'));
  
  $output = '';
  if (!$tid) {
    foreach ($displayArray as $tid => $term) {
      $output .= '<div><b>' . l(t($term['name']), 'vecommerce/sellers/catalogs/' . $tid) . '</b></div>';
      array_walk($term['child'], 'sellers_show_sellers_l');
      $output .= implode(', ', $term['child']);
    }
    
    // call customview-sellers-showrootcatalogs.tpl.php to use custom formatting
    $formattedoutput = _phptemplate_callback('customview-vecommerce-sellers-catalogs', array('output' => $output));
    
  } else {
    $term = taxonomy_get_term($tid);
    $children = taxonomy_get_children($tid);

    // show link only if leaf element
    if (empty ($children)) {
      $output .= '<ul><li>' . t($term->name) . '</li></ul>';
    } else {
      $output .= '<ul><li>' . t($term->name);
      $children_level_one = & $children;

      foreach ($children_level_one as $children_key_level_one => $children_value_level_one) {
        $children_level_two = taxonomy_get_children($children_key_level_one);
        if (empty ($children_level_two)) {
          $output .= '<ul><li>' . l($children_value_level_one->name, 'vecommerce/sellers/' . $children_key_level_one) . '</li></ul>';
        } else {

          $output .= '<ul><li>' . l($children_value_level_one->name, 'vecommerce/sellers/' . $children_key_level_one);
          foreach ($children_level_two as $children_key_level_two => $children_value_level_two) {
            $output .= '<ul><li>' . l($children_value_level_two->name, 'vecommerce/sellers/' . $children_key_level_two) . '</li></ul>';
          }
          $output .= '</li></ul>';
        }
      }
      $output .= '</li></ul>';
    }
    
    // call customview-sellers-showrootcatalogs.tpl.php to use custom formatting
    $formattedoutput = _phptemplate_callback('customview-vecommerce-sellers-catalogs-child', array('output' => $output));
    
  }
  
  return $formattedoutput;
}

function phptemplate_buyers_show_catalogs(& $displayArray, $tid = 0) {
  drupal_set_title(t('Browse buying leads by category'));
  $output = '';
  if (!$tid) {

    foreach ($displayArray as $tid => $term) {
      $output .= '<div><b>' . l(t($term['name']), 'vecommerce/buyers/catalogs/' . $tid) . '</b></div>';
      array_walk($term['child'], 'buyers_show_buyers_l');
      $output .= implode(', ', $term['child']);
    }
    $formattedoutput = _phptemplate_callback('customview-vecommerce-buyers-catalogs', array('output' => $output));
    
  } else {
    $term = taxonomy_get_term($tid);
    $children = taxonomy_get_children($tid);

    // show link only if leaf element
    if (empty ($children)) {
      $output .= '<ul><li>' . t($term->name) . '</li></ul>';
    } else {
      $output .= '<ul><li>' . t($term->name);
      $children_level_one = & $children;

      foreach ($children_level_one as $children_key_level_one => $children_value_level_one) {
        $children_level_two = taxonomy_get_children($children_key_level_one);
        if (empty ($children_level_two)) {
          $output .= '<ul><li>' . l($children_value_level_one->name, 'vecommerce/buyers/' . $children_key_level_one) . '</li></ul>';
        } else {

          $output .= '<ul><li>' . l($children_value_level_one->name, 'vecommerce/buyers/' . $children_key_level_one);
          foreach ($children_level_two as $children_key_level_two => $children_value_level_two) {
            $output .= '<ul><li>' . l($children_value_level_two->name, 'vecommerce/buyers/' . $children_key_level_two) . '</li></ul>';
          }
          $output .= '</li></ul>';
        }
      }
      $output .= '</li></ul>';
    }
    $formattedoutput = _phptemplate_callback('customview-vecommerce-buyers-catalogs-child', array('output' => $output));
  }
  
  return $formattedoutput;
}

/**
 * Customize our own front page
 * Overriding the module function at Custom Pages Handler Module (customviews/custompages.module)
 * theme_custompages_page_front 
 * 
 */
function phptemplate_custompages_page_front() {
	return _phptemplate_callback('customnode-pages-front');
}

function phptemplate_cck_address($cck_address) {
  //create the output
  $output = $cck_address['street1']. ' ';
  $output .= ($cck_address['street1'])?'<br />':'';
  $output .= ($cck_address['street2'])? ($cck_address['street2']. '<br />'):'';
  $output .= $cck_address['city']. ', ';
  $output .= $cck_address['state']. ' ';
  $output .= $cck_address['zip'];
  $output .= ' ' .cck_address_get_country_by_code($cck_address['country']);
  if ($cck_address['other'] != '') {
    $output .= '<br />' .$cck_address['other']. '<br />';
  }
  
  return $output;
} // function theme_cck_address()

function phptemplate_views_filters($form) {
	if ('sellingleads_search' != $form['#view_name'])
    return;

  drupal_add_css(path_to_theme().'/searchbar.css');
  
	//change submit button to search button
	$form['submit']['#value'] = "Search";
	
	$view = $form['view']['#value'];
	foreach ($view->exposed_filter as $count => $expose) {
	   $label = '<label for="edit-filter'.$count.'">'.$expose['label'].'</label>';
	   $formelement = drupal_render($form["op$count"]) . drupal_render($form["filter$count"]);
	   $o .= $label.$formelement;
	}
	$o .= drupal_render($form['submitx']);
	return '<div id="search_block">'.$o . drupal_render($form).'</div>';
}



/*function theme_user_profile_node_form($form) {
  $output = drupal_render($form);
	return $output;
}*/


/**
 * Overriding the theming function for the cart block 
 */
function phptemplate_cart_display_block() {
  global $user;
  $output = '';

  /**
   * Until Drupal can handle partial page caching, We should only display a
   * View Cart link for anonymous users and the full fancy items and total cart
   * for authenticated users since those pages aren't cached.
   */
  if ($user->uid == 0) {    
    $output .= l(t('View your cart'), 'cart/view');
  }
  else {

    $item = cart_get_items();
    $item_count = count($item);
    $item_suffix = ($item_count == 1) ? t('Item') : t('Items');

    $output .= '<div class="item-count">'. t("%item_count %item_suffix in !your_cart", array("%item_count" => $item_count, "%item_suffix" => $item_suffix, "!your_cart" => l(t("Your cart"), "cart/view"))). "</div>\n";

    if (!empty($item)) {
      $output .= '<div class="items">';
      foreach ($item as $i) {
        $node = node_load($i->nid);
        if (product_has_quantity($node)) {
          $total += ($i->price * $i->qty) + product_get_specials($i, 'cart', true);
          $output .= l("$node->title x $i->qty", 'node/'. ($node->pparent ? $node->pparent : $node->nid)). "<br />";
        }
        else {
          $i->qty = 1;
          $total += $i->price+product_get_specials($i, 'cart', true);
          $output .= l("$node->title", 'node/'. ($node->pparent ? $node->pparent : $node->nid)). "<br />";
        }
      }
      $output .= "</div><div class=\"total\">". payment_format($total) . "</div>";
      $output .= '<div class="checkout">'. t('Ready to <a href="!checkout-url">checkout</a>?', array('!checkout-url' => url('cart/mail'))) .'</div>';
    }
  }

  return $output;
}


/**
 * Overiding the theming function of mygamesi home
 */
function phptemplate_custompages_page_mygambesi_home($news, $mysellingleads, $mybuyingleads) {
  $str =  'edit template.php phptemplate_custompages_page_mygambesi_home() function
          <div id="news">
            <h1>'.t('News').' </h1>'.$news.
          '</div>'.
          '<div id="my-products-on-sale">'.
          '<h1>'.t(' My Products On Sale'). '</h1>'.$mysellingleads.
          '</div>'.
          '<div id="my-buying-leads">'.
          '<h1>'. t('My Buying Leads').' </h1>'.$mybuyingleads.
          '</div>';
  return $str;
}